import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BASE_URL } from '../const/base.const';

@Injectable({
  providedIn: 'root'
})
export class HttpService {
  private baseUrl: string;

  constructor(private $http: HttpClient) {
    this.baseUrl = BASE_URL;
  }

  private convertObjToHttpParam(params?: any): HttpParams {
    let httpParams = new HttpParams();
    if (params) {
      for (const key in params) {
        if (params[key] === false || params[key]) {
          httpParams = httpParams.set(key, params[key]);
        }
      }
    }

    return httpParams;
  }

  // General API.

  public get(url: string, params?: Object, options?: any) {
    let httpParams = this.convertObjToHttpParam(params);

    return this.$http.get(`${this.baseUrl}${url}`, {
      headers: Object.assign({}, options),
      params: httpParams
    });
  }

  public post(url: string, data?: Object, options?: Object) {
    return this.$http.post(`${this.baseUrl}${url}`, data, options);
  }

  public put(url: string, data?: Object, options?: Object) {
    return this.$http.put(`${this.baseUrl}${url}`, data, options);
  }

  public patch(url: string, data?: Object, options?: Object) {
    return this.$http.patch(`${this.baseUrl}${url}`, data, options);
  }

  public delete(url: string, params?: Object, options?: any) {
    let httpParams = this.convertObjToHttpParam(params);
    return this.$http.delete(`${this.baseUrl}${url}`, {
      headers: Object.assign({}, options),
      params: httpParams
    });
  }

}
